<?php
/**
 * Created by PhpStorm.
 * User: refar
 * Date: 22-5-31
 * Time: 上午9:51
 */

namespace app\tasks\controller;

use think\Exception;
use think\Log;
use think\Db;

class ClearAttachment {

    public function dog() {
        try {
            Log::record('[ClearAttachment][dog] start');

            $res1 = Db::table('sms_borrow_history')->distinct(true)->field('instore_proof')
                ->whereNotNull('instore_proof')->select();

            $res2 = Db::table('sms_borrow_history')->distinct(true)->field('assign_proof')
                ->whereNotNull('assign_proof')->select();

            $res3 = Db::table('sms_attachment')->distinct(true)->field('id')->select();

            $resIn = array_column($res1, 'instore_proof');
            $resAs = array_column($res2, 'assign_proof');
            $resAt = array_column($res3, 'id');

            // 查看是否有交集
            $r = array_intersect($resIn, $resAs);

            if (empty($r)) {
                $unionArray = [];
                foreach ($resIn as $item) {
                    $unionArray[] = $item;
                }
                foreach ($resAs as $item) {
                    $unionArray[] = $item;
                }

                foreach ($resAt as $item) {
                    if (!in_array($item, $unionArray)) {
                        Log::record('[ClearAttachment] find no use attachment ' . $item);

                        $r1 = Db::table('sms_attachment')->where('id', $item)->find();
                        if (file_exists($r1['path'])) {
                            Log::record('[ClearAttachment] clear exist no use attachment ' . $r1['path']);
                            unlink($r1['path']);

                            Db::table('sms_attachment')->where('id', $item)->delete();
                        } else {
                            Log::record('[ClearAttachment] === path not exist === ' . $r1['path']);
                        }
                    }
                }
            } else {
                Log::record('[ClearAttachment] array_intersect result not empty ' . json_encode($r));
            }
        } catch (Exception $e) {
            Log::record('[ClearAttachment][dog] error ' . $e->getMessage());
        }
        Log::record('[ClearAttachment][dog] end');
    }
}